package com.cn.http;

import cn.com.allunion.sms.pojo.Smsrecord;
import com.alibaba.fastjson.JSON;
import com.cn.http.command.SmsCommand;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 抽象的短信拦截实现
 * @author yang.jie
 * @email yang.jie@all-union.com.cn
 * @date 2016/5/5.
 * @copyright http://www.all-union.com.cn/
 */
public abstract class AbstractSmsrecordInterceptor implements SmsrecordInterceptor {
    private final static Logger LOGGER = LoggerFactory.getLogger(AbstractSmsrecordInterceptor.class) ;
    /**
     * 短信发送服务
     */
    private SmsCommand smsCommand ;

    /**
     * 执行短信发送命令前拦截
     * @param smsrecordList 要拦截的短信发送记录集合
     * @return 拦截成功返回true，否者返回false
     */
    public boolean preExecute(List<Smsrecord> smsrecordList) {
        List<Smsrecord> smsrecords = preExecuteInternal(smsrecordList) ;
        if (CollectionUtils.isNotEmpty(smsrecords)) {
            // 从原来的集合中移除被拦截的短信记录集合
            smsrecordList.removeAll(smsrecords) ;
            // 发送拦截到的短信
            sendSms(smsrecords);
            return true ;
        } 
        return false ;
    }

    /**
     * 内部执行短信发送命令前拦截，这个方法由子类来实现具体的拦截逻辑，并返回
     * 拦截到的短信集合
     * @param smsrecordList 被拦截的短信集合
     * @return 拦截到的短信集合
     */
    protected abstract List<Smsrecord> preExecuteInternal(List<Smsrecord> smsrecordList);

    /**
     * 执行发送短信
     * @param smsrecordList 要发送的短信集合
     */
    protected void sendSms(List<Smsrecord> smsrecordList) {
        if (CollectionUtils.isNotEmpty(smsrecordList) && null != smsCommand) {
            if(LOGGER.isInfoEnabled()) {
                LOGGER.info("执行发送短信命令: {}", JSON.toJSONString(smsCommand));
            }
            smsCommand.execute(smsrecordList); // 执行命令
        }
    }

    public SmsCommand getSmsCommand() {
        return smsCommand;
    }

    public void setSmsCommand(SmsCommand smsCommand) {
        this.smsCommand = smsCommand;
    }
}
